package training;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author liangzai
 * @Description:
 */
public class J25_7_16_Training {
    //找出有效子序列的最大长度 I
    public int maximumLength(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        // 查找第一个奇数和第一个偶数的位置
        int firstOddIndex = findFirstWithParity(nums, 1);
        int firstEvenIndex = findFirstWithParity(nums, 0);
        // 四种可能的子数组类型
        List<Integer> oddEvenSequence = buildAlternatingSequence(nums, firstOddIndex, true);
        List<Integer> evenOddSequence = buildAlternatingSequence(nums, firstEvenIndex, false);
        List<Integer> oddOnlySequence = buildSameParitySequence(nums, firstOddIndex, true);
        List<Integer> evenOnlySequence = buildSameParitySequence(nums, firstEvenIndex, false);

        // 返回四种情况的最大长度
        return Math.max(
                Math.max(oddEvenSequence.size(), evenOddSequence.size()),
                Math.max(oddOnlySequence.size(), evenOnlySequence.size())
        );
    }

    // 辅助方法：查找第一个满足奇偶条件的元素索引
    private int findFirstWithParity(int[] nums, int parity) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] % 2 == parity) {
                return i;
            }
        }
        return nums.length;
    }

    // 构建奇偶交替的子数组
    private List<Integer> buildAlternatingSequence(int[] nums, int startIndex, boolean startsWithOdd) {
        List<Integer> sequence = new ArrayList<>();
        if (startIndex >= nums.length) {
            return sequence;
        }
        int currentParity = startsWithOdd ? 1 : 0;
        for (int i = startIndex; i < nums.length; i++) {
            if (nums[i] % 2 == currentParity) {
                sequence.add(nums[i]);
                currentParity ^= 1;
            }
        }
        return sequence;
    }

    // 构建同奇偶性的子数组
    private List<Integer> buildSameParitySequence(int[] nums, int startIndex, boolean isOdd) {
        List<Integer> sequence = new ArrayList<>();
        if (startIndex >= nums.length) {
            return sequence;
        }

        int targetParity = isOdd ? 1 : 0;
        for (int i = startIndex; i < nums.length; i++) {
            if (nums[i] % 2 == targetParity) {
                sequence.add(nums[i]);
            }
        }
        return sequence;
    }
}
